package indi.zhifa.engine.core.excel2025.handler;

import indi.zhifa.engine.core.common.web.utils.PackageScanUtil;
import indi.zhifa.engine.core.excel2025.annotation.ExcelHandlerAnn;
import indi.zhifa.engine.core.excel2025.properties.ZfExcelProperties;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ExcelCellHandlerMemo {

    private Map<Class<?>,IExcelCellHandler> mExcelCellHandlerMap;

    public void init(ZfExcelProperties pZfExcelProperties) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        mExcelCellHandlerMap = new HashMap<Class<?>,IExcelCellHandler>();
        List<Class<?>> clsList = PackageScanUtil.scanBasePackage(pZfExcelProperties.getHandlerPaths(), ExcelHandlerAnn.class) ;
        for(Class<?> cls : clsList){
            Constructor constructor = cls.getConstructor();
            Object handler = constructor.newInstance();
            ExcelHandlerAnn excelHandlerAnn = cls.getAnnotation(ExcelHandlerAnn.class);
            for(Class<?> valType : excelHandlerAnn.valTypes()){
                mExcelCellHandlerMap.put(valType,(IExcelCellHandler)handler);
            }
        }
    }

    public IExcelCellHandler getExcelCellHandler(Class<?> fieldType) {
        if(mExcelCellHandlerMap.containsKey(fieldType)){
            return mExcelCellHandlerMap.get(fieldType);
        }
        return null;
    }
}
